package com.demo.web.pc;

import com.demo.common.Constants;
import com.demo.dto.BaseResult;
import com.demo.utils.ImageUtil;
import com.google.common.io.Files;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by liushaokang on 2017/3/15.
 * ref:http://www.iteye.com/topic/264457
 */
@Controller
public class CutImageController {

    @RequestMapping(value = "/cutimage", method = RequestMethod.POST)
    public
    @ResponseBody
    BaseResult cutImage(@RequestParam("image") MultipartFile file, HttpServletRequest request) throws IOException {
        if (file.isEmpty()) {
            return new BaseResult(false, "file is empty", 400);
        }
        int x = Integer.valueOf(request.getParameter("x"));
        int y = Integer.valueOf(request.getParameter("y"));
        int width = Integer.valueOf(request.getParameter("width"));
        int height = Integer.valueOf(request.getParameter("height"));
        if (width == 0 || height == 0) {
            return new BaseResult(false, "parameters error", 400);
        }
        //nginx访问路径
        String webPath = Constants.nginxVisitUrl;
        //图片保存路径
        String imgPath = Constants.thumbnailPath;
        String fileName = UUID.randomUUID().toString().replaceAll("-", "");
        String extension = Files.getFileExtension(file.getOriginalFilename());

        File imgBig = new File(imgPath + fileName + "_big." + extension);
        file.transferTo(imgBig);

        File imgSmall = new File(imgPath + fileName + "_small." + extension);
        imgSmall.createNewFile();

        ImageUtil.cutImage(imgBig, new FileOutputStream(imgSmall), x, y, width, height);

        return new BaseResult(true, webPath + fileName + "_small." + extension, 200);
    }

    @RequestMapping(value = "/path-cut-image", method = RequestMethod.POST)
    @ResponseBody
    public BaseResult pathCutImage(HttpServletRequest request) throws IOException {

        int x = Integer.valueOf(request.getParameter("x"));
        int y = Integer.valueOf(request.getParameter("y"));
        int width = Integer.valueOf(request.getParameter("w"));
        int height = Integer.valueOf(request.getParameter("h"));
        String path = String.valueOf(request.getParameter("path"));
        if (width == 0 || height == 0 || path == null) {
            return new BaseResult(false, "parameters error", 400);
        }
//        Resource resource = new ClassPathResource("config.properties");
//        Properties properties = new Properties();
//        properties.load(resource.getInputStream());
        //nginx访问路径
//        String webPath = properties.getProperty("nginxvisiturl");
        String webPath = Constants.nginxVisitUrl;
        String imgPath = Constants.thumbnailPath;
//        String imgPath = properties.getProperty("thumbnailpath");

        path = path.replace(webPath, imgPath);

        File imgBig = new File(path);
        String small = path.replace("_big.", "_small.");
        System.out.println(small);
        File imgSmall = new File(small);
        imgSmall.createNewFile();

        ImageUtil.cutImage(imgBig, new FileOutputStream(imgSmall), x, y, width, height);
        Map map = new HashMap();
        small = small.replace(imgPath, webPath);
        map.put("path", small);


        return new BaseResult(true, map);
    }

    @ResponseBody
    @RequestMapping(value = "/pages/error/maxUploadExceeded",method = RequestMethod.GET)
    public BaseResult handleMaxUploadSizeExceededException(Exception ex, HttpServletRequest request) {
        if (ex instanceof org.springframework.web.multipart.MaxUploadSizeExceededException) {
            return new BaseResult(false, "最大上传文件不能超过5M!", 403);
        }
        return new BaseResult(false, "服务端错误!", 500);
    }

    /***
     * @param file
     * @param type 文件类型：默认图片，papaer合同
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public BaseResult upload(@RequestParam("file") MultipartFile file, String type, HttpServletRequest request, HttpServletResponse response) throws IOException {
        if (file.isEmpty()) {
            return new BaseResult(false, "file is empty", 400);
        }
        response.setHeader("Content-type", "text/html");
        //图片保存路径
        String imgPath = null;
        String webPath = null;
        if ("paper" == type) {
            imgPath = Constants.orderpaperPath;
        } else {
            imgPath = Constants.thumbnailPath;
        }
        webPath = Constants.nginxVisitUrl;

        String fileName = UUID.randomUUID().toString().replaceAll("-", "");
        String extension = Files.getFileExtension(file.getOriginalFilename());
        String monthPath = getDayPath();
        String diskPath = imgPath + monthPath;
        File path = new File(diskPath);
        webPath += monthPath;
        if (!path.exists()) {
            path.mkdir();
        }
        File imgBig = new File(diskPath + fileName + "_big." + extension);
        file.transferTo(imgBig);

        Map map = new HashMap();
        map.put("path", webPath + fileName + "_big." + extension);
        map.put("currentFileName", file.getOriginalFilename());
        map.put("currentFileSize", fileName + "." + extension);
        map.put("currentWidth", fileName + "." + extension);
        map.put("request", "upload");
        map.put("status", true);

        return new BaseResult(true, map);
    }

    public String getDayPath() {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        String datePath = sdf.format(date) + "/";
        ;
        return datePath;
    }


}
